import { createSlice } from '@reduxjs/toolkit';
import { AppDispatch, RootState } from '@src/store';
import * as auth from '@src/auth-provider';
import { User } from '@src/types/user';
import { AuthForm, bootstrapUser } from '@src/context/auth-context';

interface State {
  user: User | null;
}

const initialState: State = {
  user: null,
};
export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setUser(state, action) {
      state.user = action.payload;
    },
  },
});

const { setUser } = authSlice.actions;

export const selectUser = (state: RootState) => state.auth.user;
//
// export const loginThunkAync = (form: AuthForm) =>
//   createAsyncThunk('user/login', async () => {
//     const res = await auth.login(form);
//     console.log('11111111111111111111111:', res);
//     return res;
//   });
//
// export const registerThunkAync = (form: AuthForm) =>
//   createAsyncThunk('user/register', async () => {
//     const res = await auth.register(form);
//     console.log('11111111111111111111111:', res);
//     return res;
//   });
//
// export const logoutThunkAync = () =>
//   createAsyncThunk('user/logout', async () => {
//     await auth.logout();
//   });
//
// export const bootstrapThunkAync = () =>
//   createAsyncThunk('user/bootstrapUser', async () => {
//     await bootstrapUser();
//   });

export const login = (form: AuthForm) => (dispatch: AppDispatch) =>
  auth.login(form).then((user) => dispatch(setUser(user)));

export const register = (form: AuthForm) => (dispatch: AppDispatch) =>
  auth.register(form).then((user) => dispatch(setUser(user)));
export const logout = () => (dispatch: AppDispatch) => auth.logout().then(() => dispatch(setUser(null)));
export const bootstrap = () => (dispatch: AppDispatch) => bootstrapUser().then((user) => dispatch(setUser(user)));
